// pages/finish/finish.js

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
import Toast from '@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order: null,
    urlGetOne: "/portal/orders/info",
    urlFinish: "/portal/orders/finish",
  },

  // 点击一键呼叫
  calling: function(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phonenumber,
      success: function() {
      console.log("拨打电话成功！")
      },
      fail: function() {
        console.log("拨打电话失败！")
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 挂载全局数据
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['user'],
      actions: ['getUser', 'getWebsite']
    });

    this.setData({
      urlGetOne: this.getWebsite() + this.data.urlGetOne,
      urlFinish: this.getWebsite() + this.data.urlFinish,
    });

    const eventChannel = this.getOpenerEventChannel();
    // 监听 acceptDataFromOpenerPage 事件，获取上一页面通过 eventChannel 传送到当前页面的数据
    var acceptId = options.id;
    console.log(acceptId);
    // eventChannel.on('acceptDataFromOpenerPage', function(data) {
    //   // 获取商品id
    //   acceptId = data.data;
    // });

    // 根据id获取订单详情信息
    this.getOrderInfo(acceptId)
  },

  getOrderInfo(id) {
    wx.request({
      url: this.data.urlGetOne,
      method: "POST",
      data: {
        orderId: id,
        riderId: this.getUser().id,
      },
      success: (result) => {
        Toast(result.data.msg);
        // 对日期格式化
        result.data.data["infoDate"] = this.formatDate(result.data.data["infoDate"]);
        result.data.data["orderAcceptTime"] = this.formatDate(result.data.data["orderAcceptTime"]);
        result.data.data["orderPostTime"] = this.formatDate(result.data.data["orderPostTime"]);
        if (result.data.data["orderFinishTime"] != null) {
          result.data.data["orderFinishTime"] = this.formatDate(result.data.data["orderFinishTime"]);
        }

        this.setData({
          order: result.data.data
        })
      },
      complete: () => {
        wx.stopPullDownRefresh();
      }
    })
  },

  formatDate (time) {
    var date = new Date(time);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = function () { //获取小时
        return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    }
    var minute = function () { //获取分钟
        return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    }

    var second = function () { //获取秒数
        return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    }
    return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
  },

  toFinish() {
    if (this.data.order == null) {
      Toast("订单获取失败");
      return;
    }

    Dialog.confirm({
      message: '确认完成订单',
    })
      .then(() => {
        // on confirm
        wx.request({
          url: this.data.urlFinish,
          method: "POST",
          data: {
            orderId: this.data.order.id,
            riderId: this.getUser().id,
          },
          success: (result) => {
            Toast(result.data.msg);
            setTimeout(() => {
              this.getOrderInfo(this.data.order.id)
            }, 1000)
          },
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });
    this.getOrderInfo(this.data.order.id);
    Toast.clear();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})